<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>多种类型图元绘制</title>

    <!-- 顶点着色器 -->
    <script id="shader-vs" type="x-shader/x-vertex">
        attribute vec3 aVertexPosition;
        attribute vec4 aVertexColor;
        varying vec4 vColor;

        void main() {
            vColor = aVertexColor;
            gl_Position = vec4(aVertexPosition, 1.0);
        }
    </script>

    <!-- 片段着色器 -->
    <script id="shader-fs" type="x-shader/x-fragment">
        precision mediump float;

        varying vec4 vColor;
        void main() {
            gl_FragColor = vColor;
        }
    </script>

    <script>
        var gl;
        var canvas;
        var shaderProgram;
        var hexagonVertexBuffer;
        var triangleVertexBuffer;
        var triangleVertexColorBuffer;
        var stripVertexBuffer;
        var stripElementBuffer;

        function createGLContext(canvas) {
            var names = ["webgl", "experimental-webgl"];
            var context = null;
            for (var i = 0; i < names.length; i++) {
                try {
                    context = canvas.getContext(names[i]);
                } catch (e) { }
                if (context) {
                    break;
                }
            }
            if (context) {
                // 添加动态属性记录画布的大小
                context.viewportWidth = canvas.width;
                context.viewportHeight = canvas.height;
            } else {
                alert("Failed to create WebGL context!");
            }
            return context;
        }

        function setupShaders() {
            // 从 DOM 上创建对应的着色器
            vertexShader = loadShaderFromDOM("shader-vs");
            fragmentShader = loadShaderFromDOM("shader-fs");

            // 创建程序并连接着色器
            shaderProgram = gl.createProgram();
            gl.attachShader(shaderProgram, vertexShader);
            gl.attachShader(shaderProgram, fragmentShader);
            gl.linkProgram(shaderProgram);

            // 连接失败的检测
            if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
                alert("Failed to setup shaders");
            }

            // 使用着色器
            gl.useProgram(shaderProgram);

            // 创建动态属性获取着色器中 aVertexPosition 属性的位置
            shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
            // 创建动态属性获取着色器中 aVertexColor 属性的位置
            shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");

            // 设定 aVertexColor 属性为数组类型的变量数据
            gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
        }

        function loadShaderFromDOM(id) {
            // 获取 DOM
            var shaderScript = document.getElementById(id);

            if (!shaderScript) {
                return null;
            }

            // 获取着色器代码
            var shaderSource = "";
            var currentChild = shaderScript.firstChild;
            while (currentChild) {
                if (currentChild.nodeType == 3) { // 3 corresponds to TEXT_NODE
                    shaderSource += currentChild.textContent;
                }
                currentChild = currentChild.nextSibling;
            }

            // 创建着色器
            var shader;
            if (shaderScript.type == "x-shader/x-fragment") {
                shader = gl.createShader(gl.FRAGMENT_SHADER);
            } else if (shaderScript.type == "x-shader/x-vertex") {
                shader = gl.createShader(gl.VERTEX_SHADER);
            } else {
                return null;
            }

            // 编译着色器
            gl.shaderSource(shader, shaderSource);
            gl.compileShader(shader);

            // 判断编译是否成功
            if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
                alert(gl.getShaderInfoLog(shader));
                return null;
            }
            return shader;
        }

        function setupBuffers() {
            // 六边形
            hexagonVertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, hexagonVertexBuffer);
            var hexagonVertices = [
                -0.3, 0.6, 0.0, //v0
                -0.4, 0.8, 0.0, //v1
                -0.6, 0.8, 0.0, //v2
                -0.7, 0.6, 0.0, //v3
                -0.6, 0.4, 0.0, //v4
                -0.4, 0.4, 0.0, //v5
                -0.3, 0.6, 0.0, //v6
            ];
            // 提交顶点数据
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(hexagonVertices), gl.STATIC_DRAW);
            hexagonVertexBuffer.itemSize = 3;
            hexagonVertexBuffer.numberOfItems = 7;

            // 三角形
            triangleVertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexBuffer);
            var triangleVertices = [
                0.3, 0.4, 0.0, //v0
                0.7, 0.4, 0.0, //v1
                0.5, 0.8, 0.0, //v2
            ];
            // 提交顶点数据
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVertices), gl.STATIC_DRAW);
            triangleVertexBuffer.itemSize = 3;
            triangleVertexBuffer.numberOfItems = 3;
            // 三角形颜色数据
            triangleVertexColorBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
            var colors = [
                1.0, 0.0, 0.0, 1.0, //v0
                0.0, 1.0, 0.0, 1.0, //v1
                0.0, 0.0, 1.0, 1.0  //v2
            ];
            // 提交顶点数据
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
            triangleVertexColorBuffer.itemSize = 4;
            triangleVertexColorBuffer.numberOfItems = 3;

            // 连续线段，使用了退化三角形
            stripVertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, stripVertexBuffer);
            var stripVertices = [
                -0.5, 0.2, 0.0, //v0
                -0.4, 0.0, 0.0, //v1
                -0.3, 0.2, 0.0, //v2
                -0.2, 0.0, 0.0, //v3
                -0.1, 0.2, 0.0, //v4
                0.0, 0.0, 0.0, //v5
                0.1, 0.2, 0.0, //v6
                0.2, 0.0, 0.0, //v7
                0.3, 0.2, 0.0, //v8
                0.4, 0.0, 0.0, //v9
                0.5, 0.2, 0.0, //v10
                // start second strip
                -0.5, -0.3, 0.0, //v11
                -0.4, -0.5, 0.0, //v12
                -0.3, -0.3, 0.0, //v13
                -0.2, -0.5, 0.0, //v14
                -0.1, -0.3, 0.0, //v15
                0.0, -0.5, 0.0, //v16
                0.1, -0.3, 0.0, //v17
                0.2, -0.5, 0.0, //v18
                0.3, -0.3, 0.0, //v19
                0.4, -0.5, 0.0, //v20
                0.5, -0.3, 0.0  //v21
            ];
            // 提交顶点数据
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(stripVertices), gl.STATIC_DRAW);
            stripVertexBuffer.itemSize = 3;
            stripVertexBuffer.numberOfItems = 22;
            // 索引缓冲
            stripElementBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, stripElementBuffer);
            var indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                10, 10, 11, // 这个是退化三角形
                11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
            // 提交顶点数据
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
            stripElementBuffer.numberOfItems = 25;
        }

        function draw() {
            gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
            gl.clear(gl.COLOR_BUFFER_BIT);

            // 绘制六边形
            // 将颜色作为常量进行提交
            gl.disableVertexAttribArray(shaderProgram.vertexColorAttribute);
            gl.vertexAttrib4f(shaderProgram.vertexColorAttribute, 0.0, 0.0, 0.0, 1.0);

            gl.bindBuffer(gl.ARRAY_BUFFER, hexagonVertexBuffer);
            gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, hexagonVertexBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.drawArrays(gl.LINE_STRIP, 0, hexagonVertexBuffer.numberOfItems);

            // 绘制三角形
            // 将颜色值作为变量进行提交
            gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

            gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexBuffer);
            gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
            gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.drawArrays(gl.TRIANGLES, 0, triangleVertexBuffer.numberOfItems);

            // 绘制连续线段
            // 将颜色作为常量进行提交
            gl.disableVertexAttribArray(shaderProgram.vertexColorAttribute);
            gl.bindBuffer(gl.ARRAY_BUFFER, stripVertexBuffer);
            gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, stripVertexBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.vertexAttrib4f(shaderProgram.vertexColorAttribute, 1, 1, 0, 1);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, stripElementBuffer);

            gl.drawElements(gl.TRIANGLE_STRIP, stripElementBuffer.numberOfItems, gl.UNSIGNED_SHORT, 0);

            // 绘制黑色辅助线帮助方便查看三角形
            gl.vertexAttrib4f(shaderProgram.vertexColorAttribute, 0, 0, 0, 1);

            gl.drawArrays(gl.LINE_STRIP, 0, 11);
            gl.drawArrays(gl.LINE_STRIP, 11, 11);
        }

        function startup() {
            canvas = document.getElementById("myGLCanvas");
            gl = createGLContext(canvas);
            setupShaders();
            setupBuffers();
            gl.clearColor(1, 1, 1, 1);

            gl.frontFace(gl.CCW);
            gl.enable(gl.CULL_FACE);
            gl.cullFace(gl.BACK);

            draw();
        }
    </script>
</head>

<body onload="startup();">
    <canvas id="myGLCanvas" width="500" height="500"></canvas>
</body>

</html>